package com.wg.net.client.websocket;

import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.websocketx.*;
import io.netty.util.CharsetUtil;

/**
 * WebSocket 协议客户端处理器
 *
 * @author 少爷123
 */
public class WebSocketClientHandler extends SimpleChannelInboundHandler<Object> {
    private static final Log log = LogFactory.get();
    private final WebSocketClientHandshaker handshaker;
    private final WebSocketClient client;
    private ChannelPromise handshakeFuture;

    public WebSocketClientHandler(WebSocketClient webSocketClient, WebSocketClientHandshaker handshaker) {
        this.handshaker = handshaker;
        this.client = webSocketClient;
    }

    public ChannelFuture handshakeFuture() {
        return handshakeFuture;
    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) {
        handshakeFuture = ctx.newPromise();
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        handshaker.handshake(ctx.channel());
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) {
        client.getWgClient().onDisconnect();
    }

    @Override
    public void channelRead0(ChannelHandlerContext ctx, Object msg) {
        Channel ch = ctx.channel();
        if (!handshaker.isHandshakeComplete()) {
            try {
                handshaker.finishHandshake(ch, (FullHttpResponse) msg);
                log.info("WebSocket Client connected!");
                handshakeFuture.setSuccess();
            } catch (WebSocketHandshakeException e) {
                log.info("WebSocket Client failure to connect");
                handshakeFuture.setFailure(e);
                client.setConnected(false);
                client.getWgClient().onConnectionFail();
            }
            return;
        }

        if (msg instanceof FullHttpResponse) {
            FullHttpResponse response = (FullHttpResponse) msg;
            throw new IllegalStateException("Unexpected FullHttpResponse (getStatus=" + response.status()
                    + ", content=" + response.content().toString(CharsetUtil.UTF_8) + ')');
        }

        WebSocketFrame frame = (WebSocketFrame) msg;
        if (frame instanceof PongWebSocketFrame) {
            log.info("WebSocket Client received pong");
        } else if (frame instanceof PingWebSocketFrame) {
            log.info("WebSocket Client received ping");
        } else if (frame instanceof CloseWebSocketFrame) {
            log.info("WebSocket Client received closing");
            ch.close();
        } else if (frame instanceof BinaryWebSocketFrame) {
            ByteBuf buf = frame.content();
            if (buf.isReadable()) {
                int packLen = buf.readInt();
                if (packLen < 1 || packLen > buf.readableBytes()) {
                    log.error("read failure: 无效包长 len={}", packLen);
                    ch.close();
                    return;
                }

                byte[] bytes = new byte[packLen];
                buf.readBytes(bytes);
                client.onReceive(bytes);
            }
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        log.error(cause);
        if (!handshakeFuture.isDone()) {
            handshakeFuture.setFailure(cause);
        }
        ctx.close();
    }
}
